//
//  AddIDCardImageViewController.m
//  DaiShengInvest
//
//  Created by 张睿 on 2017/6/29.
//  Copyright © 2017年 davinci. All rights reserved.
//

#import "AddIDCardImageViewController.h"

@interface AddIDCardImageViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
    
    UIImagePickerController *_imagePickerController;
    
}

@property (nonatomic, strong)UIAlertController * alertVC;

@property (nonatomic, weak)UIImageView * backImageView;

@property (nonatomic, weak)UILabel * topLabel;

@property (nonatomic, weak)UIView * frontView;

@property (nonatomic, weak)UIView * contraryView;

@property (nonatomic, weak)UIButton * frontButton;

@property (nonatomic, weak)UIButton * contraryButton;

@property (nonatomic, weak)UILabel * frontLabel;

@property (nonatomic, weak)UILabel * contraryLabel;

@property (nonatomic, weak)UIImageView * frontImageView;

@property (nonatomic, weak)UIImageView * contraryImage;

@property (nonatomic, weak)UIButton * nextButton;

@property (nonatomic,copy)NSString * picture;

@property (nonatomic,copy)NSString * frontURL;
@property (nonatomic,copy)NSString * contraryURL;

@end

@implementation AddIDCardImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    
    
    [self setupNavBar];
    [self setupUI];
    [self setupAlertVC];
}


- (void)setupNavBar{
    
    self.title = @"完善认证信息";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(15 * SCREENH6, 5 * SCREENH6, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"1返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToAccountView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}


- (void)setupUI{
    
    UIImageView * backImage = [[UIImageView alloc] init];
    
    backImage.image = [UIImage imageNamed:@"背景"];
    
    self.backImageView = backImage;
    
    [self.view addSubview:self.backImageView];
    
    UILabel * topLabel = [[UILabel alloc] init];
    
    topLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    topLabel.textColor = ColorWithRGB(0xcbcbcb);
    topLabel.text = @"上传身份证进行验证";
    
    self.topLabel = topLabel;
    
    [self.view addSubview:self.topLabel];
    
    UIView * frontView = [UIView new];
    
    frontView.backgroundColor = ColorWithRGB(0x0a1a21);
    
    frontView.layer.cornerRadius = 5 * SCREENH6;
    frontView.userInteractionEnabled = YES;
    frontView.layer.masksToBounds = YES;
    frontView.layer.borderColor = [ColorWithRGB(0x102b38) CGColor];
    frontView.layer.borderWidth = 1 * SCREENH6;
    
    self.frontView = frontView;
    
    [self.view addSubview:self.frontView];
    
    UIImageView * frontImage = [UIImageView new];
    
    frontImage.userInteractionEnabled = YES;
    frontImage.contentMode = UIViewContentModeScaleAspectFit;
    
    self.frontImageView = frontImage;
    
    [self.frontView addSubview:self.frontImageView];
    
    UIButton * frontButton = [UIButton new];
    
    [frontButton setImage:[UIImage imageNamed:@"添加身份证"] forState:UIControlStateNormal];
    [frontButton addTarget:self action:@selector(didAddPicture:) forControlEvents:UIControlEventTouchUpInside];
    
    self.frontButton = frontButton;
    
    [self.frontImageView addSubview:self.frontButton];
    
    UILabel * frontLabel = [[UILabel alloc] init];
    
    frontLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15 * SCREENH6];
    frontLabel.textColor = ColorWithRGB(0xcbcbcb);
    frontLabel.text = @"点击上传身份证照片（正面）";
    
    self.frontLabel = frontLabel;
    
    [self.frontImageView addSubview:self.frontLabel];
    
    
    UIView * contraryView = [UIView new];
    
    contraryView.backgroundColor = ColorWithRGB(0x0a1a21);
    
    contraryView.layer.cornerRadius = 5 * SCREENH6;
    contraryView.userInteractionEnabled = YES;
    contraryView.layer.masksToBounds = YES;
    contraryView.layer.borderColor = [ColorWithRGB(0x102b38) CGColor];
    contraryView.layer.borderWidth = 1 * SCREENH6;
    
    self.contraryView = contraryView;
    
    [self.view addSubview:self.contraryView];
    
    UIImageView * contraryImage = [UIImageView new];
    
    contraryImage.userInteractionEnabled = YES;
    contraryImage.contentMode = UIViewContentModeScaleAspectFit;
    
    self.contraryImage = contraryImage;
    
    [self.contraryView addSubview:self.contraryImage];
    
    UIButton * contraryButton = [UIButton new];
    
    [contraryButton setImage:[UIImage imageNamed:@"添加身份证"] forState:UIControlStateNormal];
    [contraryButton addTarget:self action:@selector(didAddPicture:) forControlEvents:UIControlEventTouchUpInside];
    
    self.contraryButton = contraryButton;
    
    [self.contraryImage addSubview:self.contraryButton];
    
    UILabel * contraryLabel = [[UILabel alloc] init];
    
    contraryLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15 * SCREENH6];
    contraryLabel.textColor = ColorWithRGB(0xcbcbcb);
    contraryLabel.text = @"点击上传身份证照片（背面）";
    
    self.contraryLabel = contraryLabel;
    
    [self.contraryImage addSubview:self.contraryLabel];
    
    UIButton * nextButton = [[UIButton alloc] init];
    
    [nextButton setTitle:@"提交审核" forState:UIControlStateNormal];
    nextButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:17 * SCREENH6];//
    [nextButton setBackgroundImage:[UIImage imageNamed:@"注册"] forState:UIControlStateNormal];
    nextButton.layer.borderColor = [[UIColor blackColor] CGColor];
    //边框宽度
    nextButton.layer.borderWidth =1.0f;
    //处理圆角
    nextButton.layer.cornerRadius =5.0f;
    [nextButton setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(didNextButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.nextButton = nextButton;
    
    [self.view addSubview:self.nextButton];
}


- (void)viewDidLayoutSubviews{
    
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.mas_equalTo(self.view);
    }];
 
    [self.topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.top.mas_equalTo(self.view).offset(86 * SCREENH6);
    }];
    
    [self.frontView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topLabel.mas_bottom).offset(17 * SCREENH6);
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(- 15 * SCREENH6);
        make.height.mas_equalTo(180 * SCREENH6);
    }];
    
    [self.frontImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.mas_equalTo(self.frontView);
    }];
    
    [self.frontButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.frontView).offset(35 * SCREENH6);
        make.leading.mas_equalTo(self.frontView).offset(128 * SCREENH6);
        make.trailing.mas_equalTo(self.frontView).offset(-128 * SCREENH6);
        make.height.mas_equalTo(78 * SCREENH6);
    }];
    
    [self.frontLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.frontButton.mas_bottom).offset(10 * SCREENH6);
        make.centerX.mas_equalTo(self.frontView);
    }];
    
    [self.contraryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.mas_equalTo(self.frontView);
        make.top.mas_equalTo(self.frontView.mas_bottom).offset(20 * SCREENH6);
    }];
    
    [self.contraryImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.mas_equalTo(self.contraryView);
    }];
    
    [self.contraryButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.mas_equalTo(self.frontButton);
        make.top.mas_equalTo(self.contraryView).offset(35 * SCREENH6);
    }];
    
    [self.contraryLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.frontLabel);
        make.top.mas_equalTo(self.contraryButton.mas_bottom).offset(10);
    }];
    
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contraryView.mas_bottom).offset(29 * SCREENH6);
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(-15 * SCREENH6);
    }];
}


- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo

{
    
    if ([self.picture isEqual: @"front"]){
        
        self.frontButton.hidden = YES;
        self.frontLabel.hidden = YES;
        self.frontImageView.image = image;
       
        
    }else{
        self.contraryButton.hidden = YES;
        self.contraryLabel.hidden = YES;
        
        self.contraryImage.image = image;
    }
    
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
        
    {
        //图片存入相册
        
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        
    }
    
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

//进入拍摄页面点击取消按钮

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}



- (void)didAddPicture:(UIButton *)button{
    
    if (button == self.frontButton) {
        
        self.picture = @"front";
    }else{
        
        self.picture = @"cont";
    }
    
    [self presentViewController:self.alertVC animated:YES completion:nil];
    
}


- (void)didNextButton{
    
    if (self.frontImageView.image && self.contraryImage.image) {
       
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        NSURLSessionDataTask *task = [[NetworkTool sharedTools] POST:@"site/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
            
            NSData *frontImageData = UIImageJPEGRepresentation(self.frontImageView.image,1);
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat =@"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *frontFileName = [NSString stringWithFormat:@"front%@.jpg", str];
            
            //上传的参数(上传图片，以文件流的格式)
            [formData appendPartWithFileData:frontImageData
                                        name:@"file"
                                    fileName:frontFileName
                                    mimeType:@"image/jpeg"];
            
        } progress:^(NSProgress *_Nonnull uploadProgress) {
            //打印下上传进度
        } success:^(NSURLSessionDataTask *_Nonnull task,NSDictionary * _Nullable responseObject) {
            //上传成功
            NSDictionary * dict = responseObject[@"param"];
            self.frontURL = dict[@"url"];
            
        } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
            //上传失败
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"图片上传失败，请重新上传"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }];
        
        
        NSURLSessionDataTask *task1 = [[NetworkTool sharedTools] POST:@"site/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
            
            NSData *contraryImageData = UIImageJPEGRepresentation(self.contraryImage.image,1);
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat =@"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *contraryFileName = [NSString stringWithFormat:@"contrary%@.jpg", str];
            
            //上传的参数(上传图片，以文件流的格式)
            [formData appendPartWithFileData:contraryImageData
                                        name:@"file"
                                    fileName:contraryFileName
                                    mimeType:@"image/jpeg"];
            
        } progress:^(NSProgress *_Nonnull uploadProgress) {
            //打印下上传进度
        } success:^(NSURLSessionDataTask *_Nonnull task,NSDictionary * _Nullable responseObject) {
            //上传成功
            NSDictionary * dict = responseObject[@"param"];
            self.contraryURL = dict[@"url"];
            
            [self postNewNetWorking];
        } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
            //上传失败
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"图片上传失败，请重新上传"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }];
    }else{
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"上传身份证照片后才能提交申请！"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  //响应事件
                                                                  //                                                                  NSLog(@"action = %@", action);
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
   
    
    
}

- (void)postNewNetWorking{
    
    if (self.frontURL && self.contraryURL) {
        
        NSDictionary * parametersDic = @{@"cardPositive":self.frontURL,@"cardBack":self.contraryURL};
        
        [[NetworkTool sharedTools] POST:@"user/card-img" parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            NSString * codeString = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
            
            if ([codeString isEqualToString:@"0"]) {
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:@"提交成功，请耐心等待审核。"
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
                                                                          [self.navigationController popViewControllerAnimated:YES];
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
                
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseObject[@"msg"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
                                                                          NSLog(@"action = %@", action);
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
                
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSLog(@"%@",error);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"图片上传失败，请重新上传"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }];
    }
    
    
}

- (void)backToAccountView{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
